#include "query.h"

Query::Query(QString query)
{
    m_query = query;
    m_offset = 0;
    m_limit = 0;
}

Query Query::where(QString where)
{
    if(where.isNull()) {
       return *this;
    }

    Query newQuery(*this);

    newQuery.m_where.append(where);
    return newQuery;
}

Query Query::orderBy(QString order)
{
    if(order.isNull()) {
       return *this;
    }

    Query newQuery(*this);

    newQuery.m_orderBy.append(order);
    return newQuery;
}

Query Query::limit(unsigned long limit)
{
    Query newQuery(*this);

    newQuery.m_limit = limit;
    return newQuery;
}

Query Query::offset(unsigned long offset)
{
    Query newQuery(*this);

    newQuery.m_offset = offset;
    return newQuery;
}

QString Query::build()
{
    QString query(m_query);

    for(int i=0; i<m_where.length(); i++) {
        if(!i) {
            query.append(" where ");
        } else {
            query.append(" and ");
        }
        query.append(m_where.at(i));
    }

    for(int i=0; i<m_orderBy.length(); i++) {
        if(!i) {
            query.append(" order by ");
        } else {
            query.append(", ");
        }
        query.append(m_orderBy.at(i));
    }

#ifdef FIREBIRD
    if(m_limit) {
        query.append(" first ");
        query.append(QString::number(m_limit));
    }

    if(m_offset) {
        query.append(" skip ");
        query.append(QString::number(m_offset));
    }
#endif

#ifdef DEFAULTSQL
    if(m_limit) {
        query.append(" limit ");
        query.append(QString::number(m_limit));

        if(m_offset) {
            query.append(", ");
            query.append(QString::number(m_offset));
        }
    }
#endif

    return query;
}
